<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>扇形的选择拖拽</title>
    <style>
        body{margin: 0;overflow: hidden}
        #canvas{background: antiquewhite;}
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
    const canvas=document.getElementById('canvas');
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;
    const  ctx=canvas.getContext('2d');

    //扇形
    class Sector{
        constructor(r=0,startAngle=0,endAngle=Math.PI*2,color='#000'){
            this.r=r;
            this.startAngle=startAngle;
            this.endAngle=endAngle;
            this.color=color;
            this.x=0;
            this.y=0;
        }
        draw(ctx){
            const {x,y,r,startAngle,endAngle,color}=this;
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(x,y);
            ctx.arc(x,y,r,startAngle,endAngle);
            ctx.closePath();
            ctx.fillStyle=color;
            ctx.fill();
            ctx.restore();
        }
    }

    /*扇形弧度设置则：起始弧度和结束弧度都大于0*/
    const sector = new Sector(200,0,Math.PI/3);
    sector.x=200;
    sector.y=200;
    render();

    /*鼠标拖拽*/
    //鼠标位减图形位
    let subPos=null;
    //鼠标是否在图形中
    let drag=false;

    //点击事件
    canvas.addEventListener('mousedown',mousedownFn);
    //移动
    canvas.addEventListener('mousemove',mousemoveFn);
    //鼠标抬起
    canvas.addEventListener('mouseup',mouseupFn);

    function mousedownFn(event){
        //鼠标位置
        const mousePos=getMousePos(event);
        //鼠标位减图形位
        subPos={
            x:mousePos.x-sector.x,
            y:mousePos.y-sector.y,
        };
        //判断鼠标是否在图形中
        drag=containPoint(sector,mousePos);
    }
    function mousemoveFn(event){
        const mousePos=getMousePos(event);
        if(drag){
            sector.x=mousePos.x-subPos.x;
            sector.y=mousePos.y-subPos.y;
            render();
        }
    }
    function mouseupFn(event){
        drag=false;
    }

    //判断点是否在图形中
    function containPoint(obj,mousePos){
        const {r,startAngle,endAngle}=obj;

        //获取鼠标到圆心的距离
        const len=Math.sqrt(subPos.x*subPos.x+subPos.y*subPos.y);

        //判断鼠标到圆心的距离是否小于半径
        const b1=len<r;

        //获取鼠标位减图形位的方向 dir
        let dir=Math.atan2(subPos.y,subPos.x);
        if(dir<0){dir+=Math.PI*2}

        //判断鼠标向量的方向是否在扇形的夹角之间
        let b2=dir>startAngle&&dir<endAngle;


        return b1&&b2;
    }

    //获取鼠标位置
    function getMousePos(event){
        //获取鼠标位置
        const {clientX,clientY}=event;
        //获取canvas 边界位置
        const {top,left}=canvas.getBoundingClientRect();
        //计算鼠标在canvas 中的位置
        const x=clientX-left;
        const y=clientY-top;
        return {x,y};
    }


    function render(){
        ctx.clearRect(0,0,canvas.width,canvas.height);

        sector.draw(ctx);
    }

</script>
</body>
</html>
